package com.java2302.manufacturing.controller;


import com.java2302.manufacturing.entity.SysUser;
import com.java2302.manufacturing.service.UserService;
import com.java2302.manufacturing.vo.ResultVo;
import com.java2302.manufacturing.vo.UserVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {

    @PreAuthorize("hasAuthority('user:delete')")
    @DeleteMapping("{id}")
    public ResultVo delete(@PathVariable int id){
        return ResultVo.success("删除用户成功",null);
    }
    //用户的新增权限
    @PreAuthorize("hasAuthority('user:add')")
    @PostMapping
    public ResultVo save(UserVo userVo){
        return ResultVo.success("新增用户成功",null);
    }
    @GetMapping("info")
    public ResultVo info(){
        UserDetails loginUser = (UserDetails) SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();
        UserVo userVo = new UserVo();
        userVo.setUsername(loginUser.getUsername());
        userVo.setPermissions(new ArrayList<>());
        loginUser.getAuthorities().forEach(grantedAuthority -> {
            userVo.getPermissions().add(grantedAuthority.getAuthority());
        });
        return ResultVo.success("",userVo);
    }

    @Resource
    UserService userService;
    @PostMapping("query")
    public ResultVo query(){
        Map<String,Object> map = new HashMap<String,Object>();
        List<SysUser> list = userService.query();
        map.put("list",list);
        map.put("total",list.size());
        return ResultVo.success("",map);
    }

}
